<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <title>语音通话</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=0.7, user-scalable=no, shrink-to-fit=no">
</head>
<body>
<div>
   <div>
       <input th:type="text" name="loginUserId" />
       <input th:type="button" th:value="登录" onclick="login()">
   </div>
    <div>
        <input th:type="text" name="callUserId" />
        <input th:type="button" th:value="呼叫" onclick="call()">
    </div>
    <div>
        <input th:type="button" th:value="取消通话" onclick="cancelCall()">
        <input th:type="button" th:value="麦克风" onclick="setMicMute()">
        <input th:type="button" th:value="登出" onclick="logout()">
    </div>
</div>
<script th:src="@{/static/js/trtc.js}"></script>
<script th:src="@{/static/js/tim-js.js}"></script>
<script th:src="@{/static/js/tsignaling-js.js}"></script>
<script th:src="@{/static/js/trtc-calling-js.js}"></script>
<script th:src="@{/static/js/GenerateTestUserSig.js}"></script>
<script th:src="@{/static/js/lib-generate-test-usersig.min.js}"></script>
    <script>

        //创建 TRTCCalling 对象
        let options = {
            SDKAppID: 1400471674 // 接入时需要将0替换为您的 SDKAppID
        };
        const trtcCalling = new TRTCCalling(options);

        var userId ;
        let  client ;
        // 完成登录
        function login(){
            userId = document.getElementsByName("loginUserId")[0].value;
            var userSig = genTestUserSig(userId).userSig
            client = TRTC.createClient({
                mode: 'rtc',
                sdkAppId:1400471674,
                userId:userId,
                userSig:userSig
            });
        }
        //呼叫某个用户
        function call(){
            var userID = document.getElementsByName("callUserId")[0].value;
            trtcCalling.call({
                userID,  //用户 ID
                type: 1, //通话类型，0-未知， 1-语音通话，2-视频通话
                timeout:30  //邀请超时时间, 单位 s(秒)
            });
        }

        //取消呼叫、结束通话
        function cancelCall() {
            trtcCalling.hangup();
        }

        // 群呼
        //groupID 不为空就是群呼反之逐一通知
        function groupCall() {
            trtcCalling.groupCall({userIDList, type, groupID});
        }

        //事件订阅
        let handleInvite = function ({inviteID, sponsor, inviteData}) {
            console.log(`inviteID: ${inviteID}, sponsor: ${sponsor}, inviteData: ${JSON.stringify(inviteData)}`);

            var roomID = inviteData.roomID;
            var callType = inviteData.callType;
            var isBusy =  0;

            if (inviteID != ""){
               if (confirm("【"+sponsor+"】打来电话是否接听？")){
                   client
                       .join({ roomID })
                       .catch(error => {
                           console.error('进房失败 ' + error);
                       })
                       .then(() => {
                           console.log('进房成功');
                       });
               } else {

               }
            }
        };
        trtcCalling.on('onInvited', handleInvite, this);


        // 邀请方事件回调 - 用户拒绝通话
        function handleInviteeReject({userID}) {
            alert("用户【"+userID+"】已拒绝通话")
        }
        trtcCalling.on(TRTCCalling.EVENT.REJECT, handleInviteeReject)

        // 邀请方事件回调 - 邀请用户无应答
        function handleNoResponse({userID}) {
            alert("用户【"+userID+"】无应答")
        }
        trtcCalling.on(TRTCCalling.EVENT.NO_RESP, handleNoResponse)

        // 邀请方事件回调 - 被邀请方正在通话中，忙线
        function handleNoResponse({userID}) {
            alert("用户【"+userID+"】正忙，请稍后再拨")
        }
        trtcCalling.on(TRTCCalling.EVENT.LINE_BUSY, handleNoResponse)

        // 邀请方事件回调 - 本次通话被取消了
        function handleNoResponse({userID}) {
            alert("用户【"+userID+"】已取消本次通话")
        }
        trtcCalling.on(TRTCCalling.EVENT.CALLING_CANCEL, handleNoResponse)

        // 邀请方事件回调 - 本次通话超时未应答
        function handleNoResponse({userID}) {
            alert("用户【"+userID+"】超时未应答")
        }
        trtcCalling.on(TRTCCalling.EVENT.CALLING_TIMEOUT, handleNoResponse)

        // 本次通话结束
        function handleCallEnd() {
            alert("本次通话结束")
        }
        trtcCalling.on(TRTCCalling.EVENT.CALL_END, handleCallEnd)

        var bol = true;
        // 开启、关闭麦克风
        function setMicMute() {
            trtcCalling.setMicMute(bol) // 开启麦克风
            if (bol){
                bol = false;
                console.log("开启麦克风")
            } else {
                bol = true;
                console.log("关闭麦克风")
            }

        }
        // 监听异常
        let onError = function(error) {
            console.log("异常："+error)
        };
        trtcCalling.on(TRTCCalling.EVENT.ERROR, onError);

        //登出接口
        function logout(){
            trtcCalling.logout()
        }
        const localStream = TRTC.createStream({ userId, audio: true, video: true });

        localStream
            .initialize()
            .catch(error => {
                console.error('初始化本地流失败 ' + error);
            })
            .then(() => {
                console.log('初始化本地流成功');
            });

        client
            .publish(localStream)
            .catch(error => {
                console.error('本地流发布失败 ' + error);
            })
            .then(() => {
                console.log('本地流发布成功');
            });
        client.on('stream-added', event => {
            const remoteStream = event.stream;
            console.log('远端流增加: ' + remoteStream.getId());

            //订阅远端流
            client.subscribe(remoteStream);
        });
        client.on('stream-subscribed', event => {
            const remoteStream = event.stream;
            console.log('远端流订阅成功：' + remoteStream.getId());

            // 播放远端流
            remoteStream.play('remote_stream-' + remoteStream.getId());
        });
        localStream
            .initialize()
            .catch(error => {
                console.error('初始化本地流失败 ' + error);
            })
            .then(() => {
                console.log('初始化本地流成功');
                localStream.play('local_stream');
            });
        client.on('stream-subscribed', event => {
            const remoteStream = event.stream;
            console.log('远端流订阅成功：' + remoteStream.getId());

            // 播放远端流
            remoteStream.play('remote_stream-' + remoteStream.getId());
        });
        client
            .leave()
            .then(() => {
                // 退房成功，可再次调用client.join重新进房开启新的通话。
            })
            .catch(error => {
                console.error('退房失败 ' + error);
                // 错误不可恢复，需要刷新页面。
            });


    </script>
</body>

</html>